package com.zhiqian.rpc;

import com.zhiqian.bean.RpcRequest;
import com.zhiqian.bean.RpcResponse;
import com.zhiqian.serializer.CommonDecoder;
import com.zhiqian.serializer.CommonEncoder;
import com.zhiqian.serializer.impl.HessianSerializer;
import com.zhiqian.service.RpcClient;
import com.zhiqian.service.ServiceRegistry;
import com.zhiqian.service.impl.ZookeeperServiceRegistry;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

@Slf4j
public class NettyClient implements RpcClient {

    private static final Bootstrap bootstrap;
    private ServiceRegistry serviceRegistry;

    static{
        EventLoopGroup eventExecutors = new NioEventLoopGroup();
        bootstrap=new Bootstrap();
        bootstrap.group(eventExecutors)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new CommonEncoder(new HessianSerializer()))//编码器
                        .addLast(new CommonDecoder())//解码器
                        .addLast(new NettyClientHandler());//处理器
                    }
                });
    }
    public NettyClient(String host){
        serviceRegistry=new ZookeeperServiceRegistry(host);
    }


    @Override
    public Object sendRequest(RpcRequest rpcRequest) {
        try{
            InetSocketAddress inetSocketAddress = serviceRegistry.lookupService(rpcRequest.getInterfaceName());
            ChannelFuture channelFuture = bootstrap.connect(inetSocketAddress).sync();//启动连接
            log.info("客户端连接到服务器{}",inetSocketAddress);
            Channel channel = channelFuture.channel();
            if(channel!=null){
                channel.writeAndFlush(rpcRequest).addListener(future -> {
                    if (future.isSuccess()){
                        log.info(String.format("客户端发送消息：%s",rpcRequest.toString()));
                    }else{
                        log.error("客户端发送消息有错误:{}",future.cause());
                    }
                });
                channel.closeFuture().sync();//监听关闭事件
                //下面两步是阻塞获取返回结果
                AttributeKey<RpcResponse> key = AttributeKey.valueOf("rpcResponse");
                RpcResponse response = channel.attr(key).get();
                return response;
            }
        } catch (InterruptedException e) {
            log.error("发送消息时有错误：{}",e);
        }
        return null;
    }
}
